/*
 * File Name:               Sequence_X.cs
 * 
 * Description:             普通类
 * Author:                  lisiyu <576603306@qq.com>

 * Create Date:             2017/06/13
 */

using BehaviorDesigner.Runtime.Tasks;
using System.Collections.Generic;
using System;

namespace XBehaviorTree
{
    [System.Serializable]
    public class Sequence_BTree : ITask_BTree
#if XBTREE_DEBUG
        , ITask_Debug
#endif
    {
        public ITask_BTree[] mChilds;

#if XBTREE_DEBUG
        public string FriendlyName { get; set; }
        public TaskStatus DebugStatus { get; set; }
        public bool ViewChild { get; set; }

        public void OnResetDebugStatus()
        {
            if (mChilds == null)
                return;

            DebugStatus = TaskStatus.Inactive;
            foreach (var item in mChilds)
            {
                (item as ITask_Debug).OnResetDebugStatus();
            }
        }

        public TaskStatus OnDebugUpdate()
        {
            if (mChilds == null)
            {
                DebugStatus = TaskStatus.Failure;
                return DebugStatus;
            }

            OnResetDebugStatus();

            foreach (var item in mChilds)
            {
                if ((item as ITask_Debug).OnDebugUpdate() != TaskStatus.Success)
                {
                    DebugStatus = TaskStatus.Failure;
                    return DebugStatus;
                }
            }

            DebugStatus = TaskStatus.Success;
            return DebugStatus;
        }

        public Sequence_BTree(string friendlyName, ITask_BTree[] childs)
        {
            FriendlyName = friendlyName;
            mChilds = childs;
        }
#endif

        public Sequence_BTree(ITask_BTree[] childs)
        {
            mChilds = childs;
        }

        public TaskStatus OnUpdate()
        {
            if (mChilds == null)
                return TaskStatus.Failure;

            var length = mChilds.Length;
            var i = 0;
            while (i < length)
            {
                var item = mChilds[i];
                if ((int)item.OnUpdate() != (int)TaskStatus.Success)
                    return TaskStatus.Failure;
                i += 1;
            }
            return TaskStatus.Success;
        }

        public static ITask_BTree parse(Sequence seq)
        {
            var childs = new List<ITask_BTree>();

            foreach (var item in seq.Children)
            {
                if (!item.Disabled)
                    childs.Add(XBehaviorTree.parse(item));
            }

#if XBTREE_DEBUG
            return new Sequence_BTree(seq.FriendlyName, childs.ToArray());
#else
            return new Sequence_BTree(childs.ToArray());
#endif
        }
    }
}
